package 数组;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class L39 {

    public static void main(String[] args) {
        int[] candidates = new int[]{2, 3, 5};
        int target = 8;
        List<List<Integer>> lists = new L39().combinationSum(candidates, target);
        for (List<Integer> list : lists) {
            for (Integer i : list) {
                System.out.print(i + " ");
            }
            System.out.println();
        }
    }

    /**
     * 需要运用到回溯的思想
     */

    public List<List<Integer>> combinationSum(int[] candidates, int target) {

        List<List<Integer>> lists = new ArrayList<>();
        List<Integer> combine = new ArrayList<>();
        dfs(candidates, target, lists, combine, 0);
        return lists;
    }

    // idx 表示遍历数组下标
    private void dfs(int[] candidates, int target, List<List<Integer>> lists, List<Integer> combine, int idx) {
        if (idx == candidates.length) {
            return;
        }
        if (target == 0) {
            lists.add(new ArrayList<>(combine));
            return;
        }

        dfs(candidates, target, lists, combine, idx + 1);
        // 选择当前数
        if (target - candidates[idx] >= 0) {
            combine.add(candidates[idx]);
            dfs(candidates, target - candidates[idx], lists, combine, idx);
            combine.remove(combine.size() - 1);
        }
    }
}
